package com.yvan.leto;

import com.yvan.YvanUtil;
import com.yvan.platform.StringUtils;
import lombok.SneakyThrows;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/6/27.
 */
public class RevUtils {

    private static final String FMT_REV_KEY = "${env}:${project}";

    private static final String LETO_REV = "leto-rev_id";

    private static Map<String,String> revMap = new HashMap<>();

    @SneakyThrows
    public static String getRevId(String env,String project) {

        final String revIdKey = StringUtils.format(FMT_REV_KEY)
                .set("env", env)
                .set("project", project)
                .build();
        String revId;
        if(revMap.containsKey(revIdKey)){
            revId = revMap.get(revIdKey);
        }else{
            String revIdFilePath = LetoManage.appConfig.cachePath + "/" + env + "/" + project + "/" + LETO_REV;
            File file = new File(revIdFilePath);
            revId = YvanUtil.readFile(file);
            revMap.put(revIdKey,revId);
        }

        return revId;
    }

    public static void setRevId(String env,String project,String revId) {
        saveRevIdToFile(env,project,revId);
        final String revIdKey = StringUtils.format(FMT_REV_KEY)
                .set("env", env)
                .set("project", project)
                .build();
        revMap.put(revIdKey,revId);
    }

    private static void saveRevIdToFile(String env,String project,String revId){
        String revIdFilePath = LetoManage.appConfig.cachePath + "/" + env + "/" + project + "/" + LETO_REV;
        YvanUtil.saveToFile(revIdFilePath,revId);
    }


    //TODO need change zk revid
}
